package com.qidian.server.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.sql.Timestamp;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import com.qidian.common.Constants;
import com.qidian.common.Globals;
import com.qidian.common.MessageStatus;
import com.qidian.common.TransType;
import com.qidian.common.beans.AccountBean;
import com.qidian.common.beans.AnswerType;
import com.qidian.common.beans.ClientBean;
import com.qidian.common.beans.GameTypeBean;
import com.qidian.common.beans.LoggerRecordBean;
import com.qidian.common.beans.MessageBean;
import com.qidian.common.beans.StasticClientBean;
import com.qidian.common.beans.UserBean;
import com.qidian.server.MServer;
import com.qidian.server.Status;
import com.qidian.util.PageList;

public class AdminServlet extends HttpServlet
{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 575190150385637446L;
	private static final Logger logger = Logger.getLogger(AdminServlet.class.getName()) ;
	private static final MServer mserver = MServer.getInstance() ;
	
	public void init()
	{
		
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException 
	{
		Status status = Status.OK ;
		String actionType = request.getParameter(ServletConstants.arg_action_type) ;
		response.setCharacterEncoding("utf8");
		response.setContentType("") ;
		try
		{
    		// 检查参数
    		if (actionType == null)
    		{
    		    status = Status.INVALID_ARGUMENT ;
    	        RequestDispatcher disp = request.getRequestDispatcher("/modules/admin/login.html") ;
    	        disp.forward(request, response) ;
    	        return ;
    		}
    		else if ("login".equalsIgnoreCase(actionType))
    			status = login(request,response) ;
    		else if ("logout".equalsIgnoreCase(actionType))
    			status = logout(request,response) ;
    		else if ("getMsgStatus".equalsIgnoreCase(actionType))
    			status = getMsgStatus(request,response) ;
    		// 该语句以后执行的动作需要判断session变量
    		else if (!Globals.isSuperUser(request.getSession().getAttribute(ServletConstants.s_attr_user)))
    			status = Status.LOGIN_FIRST ;
    		else if ("getQueryGameTypeDlg".equalsIgnoreCase(actionType))
    			status = getQueryGameTypeDlg(request,response) ;
    		else if ("queryGameType".equalsIgnoreCase(actionType))
    			status = queryGameType(request,response) ;
    		else if ("querySingleGameType".equalsIgnoreCase(actionType))
    			status = querySingleGameType(request,response) ;
    		else if ("updateGameType".equalsIgnoreCase(actionType))
    			status = updateGameType(request,response) ;
    		else if ("createGameType".equalsIgnoreCase(actionType))
    			status = createGameType(request,response);
    		else if ("getCreateGameTypeDlg".equalsIgnoreCase(actionType))
    			status = getCreateGameTypeDlg(request,response) ;
    		else if ("deleteGameType".equalsIgnoreCase(actionType))
    			status = deleteGameType(request,response) ;
    		else if ("getQueryAnswerRecordDlg".equalsIgnoreCase(actionType))
    			status = getQueryAnswerRecordDlg(request,response) ;
    		else if ("queryAnswerRecord".equalsIgnoreCase(actionType))
    			status = queryAnswerRecord(request,response) ;
    		else if ("getChangeModeDlg".equalsIgnoreCase(actionType))
    			status = getChangeModeDlg(request,response) ;
    		else if ("changeMode".equalsIgnoreCase(actionType))
    			status = changeMode(request,response) ;
    		else if ("getQueryClientDlg".equalsIgnoreCase(actionType))
    			status = getQueryClientDlg(request,response) ;
    		else if ("getQueryUserDlg".equalsIgnoreCase(actionType))
    			status = getQueryUserDlg(request,response) ;
    		else if ("getQueryAccountDlg".equalsIgnoreCase(actionType))
    			status = getQueryAccountDlg(request,response) ;
    		else if ("queryClient".equalsIgnoreCase(actionType))
    			status = queryClient(request,response) ;
    		else if ("queryUser".equalsIgnoreCase(actionType))
    			status = queryUser(request,response) ;
    		else if ("queryAccount".equalsIgnoreCase(actionType))
    			status = queryAccount(request,response) ;
    		else if ("getCreateClientDlg".equalsIgnoreCase(actionType))
    			status = getCreateClientDlg(request,response) ;
    		else if ("createClient".equalsIgnoreCase(actionType))
    			status = createClient(request,response) ;
    		else if ("querySingleClient".equalsIgnoreCase(actionType))
    			status = querySingleClient(request,response) ;
    		else if ("updateClient".equalsIgnoreCase(actionType))
    			status = updateClient(request,response) ;
    		else if ("deleteClient".equalsIgnoreCase(actionType))
    			status = deleteClient(request,response) ;
    		else if ("deleteUser".equalsIgnoreCase(actionType))
    			status = deleteUser(request,response) ;
    		else if ("querySingleAccount".equalsIgnoreCase(actionType))
    			status = querySingleAccount(request,response) ;
    		else if ("getLoggerDlg".equalsIgnoreCase(actionType))
    			status = getQueryLoggerDlg(request,response) ;
    		else if ("queryLogger".equalsIgnoreCase(actionType))
    			status = queryLogger(request,response) ;
    		else if ("getServerStatus".equalsIgnoreCase(actionType))
    			status = getServerStatus(request,response) ;
    		else if ("updateUser".equalsIgnoreCase(actionType))
    			status = updateUser(request,response) ;
    		else if ("switchServer".equalsIgnoreCase(actionType))
    			status = switchServer(request,response) ;
    		else if ("getSwitchServerDlg".equalsIgnoreCase(actionType))
    			status = getSwitchServerDlg(request,response) ;
    		else if ("freezeAccount".equalsIgnoreCase(actionType))
    			status = freezeAccount(request,response) ;
    		else if ("unfreezeAccount".equalsIgnoreCase(actionType))
    			status = unfreezeAccount(request,response) ;
    		else if ("freezeUser".equalsIgnoreCase(actionType))
    			status = freezeUser(request,response) ;
    		else if ("unfreezeUser".equalsIgnoreCase(actionType))
    			status = unfreezeUser(request,response) ;
    		else if ("getStasticClientDlg".equalsIgnoreCase(actionType))
    			status = getStasticClientDlg(request,response) ;
    		else if ("stasticClient".equalsIgnoreCase(actionType))
    			status = stasticClient(request,response) ;
    		else 
    			status = Status.INVALID_ARGUMENT ;
		}
		catch(Exception e)
		{
		    e.printStackTrace() ;
		    logger.error(e.getMessage()) ;
		    status = Status.OTHER_ERROR ;
		}
		if (status != Status.OK)
		{
			response.setContentType("text/html");
		    response.getWriter().write(status.description) ;
		}
	}
	private Status unfreezeUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String username = request.getParameter(ServletConstants.arg_user_name) ;
		Status status = mserver.s_unfreezeUser(username);
		if (status == Status.OK)
		{
			response.getWriter().write(status.statusCode.toString()) ;
		}
		return status;
	}

	private Status freezeUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String username = request.getParameter(ServletConstants.arg_user_name) ;
		Status status = mserver.s_freezeUser(username);
		if (status == Status.OK)
		{
			response.getWriter().write(status.statusCode.toString()) ;
		}
		return status;
	}

	private Status getMsgStatus(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		response.getWriter().write(Globals.getMessageBuffer().mscounter.toJSON());
		return Status.OK ;
	}

	private Status updateUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String strUserId = request.getParameter(ServletConstants.arg_user_id) ;
		String strReturnRatio = request.getParameter(ServletConstants.arg_return_ratio) ;
		
		if(strUserId == null || strReturnRatio == null )
			return Status.INVALID_ARGUMENT ;

		long userId = -1L ;
		double returnRatio = 0.0f ;
		try{
			userId = Long.parseLong(strUserId) ;
			returnRatio = Double.parseDouble(strReturnRatio) ;
		}
		catch(Exception e)
		{
			return Status.INVALID_VALUE ;
		}
		
		Status status = mserver.s_updateUser(userId, returnRatio) ;

		if(status == Status.OK)
			response.getWriter().write(Status.OK.toString()) ;
		
		return status;
	}

	private Status getServerStatus(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>服务器状态</h3>");
        		result.append("<div nowrap>") ;
                        	result.append("<p>");
                        	result.append("<label>服务器队列</label>").append(Globals.getMessageBuffer().getWaitSize());
                        	result.append("</p><p>");
                        	result.append("<label>待转发队列</label>").append(Globals.getMessageBuffer().getTransSize());
                        	result.append("</p><p>");
                        	result.append("<label>第一队列</label>").append(Globals.getMessageBuffer().getFirstWaitSize());
                        	result.append("</p><p>");
                        	result.append("<label>第二队列</label>").append(Globals.getMessageBuffer().getSecondWaitSize());
                        	result.append("</p><p>");
                        	result.append("<label>第三队列</label>").append(Globals.getMessageBuffer().getThirdWaitSize());
                        	result.append("</p><p>");
                        	result.append("<label>缓存消息数量</label>").append(Globals.getMessageBuffer().size());
                        	result.append("</p><p>");
                        	result.append("<label>缓存用户数量</label>").append(Globals.getUserBuffer().size());
                        	result.append("</p><p>");
                        	result.append("<label>缓存子账号数量</label>").append(Globals.getAccountBuffer().size());
                        	result.append("</p><p>");
                        	result.append("<label>缓存客户端数量</label>").append(Globals.getClientBuffer().size());
                        	result.append("</p><p>");
                        	result.append("<label>消息状态</label>").append(Globals.getMessageBuffer().mscounter);
                        	
                result.append("</p></div>") ;
        result.append("</form>") ;

		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}

	private Status queryLogger(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String operation = request.getParameter(ServletConstants.arg_operation) ;
		String operator = request.getParameter(ServletConstants.arg_operator) ;
		String operaA = request.getParameter(ServletConstants.arg_operat_A) ;
		String operaB = request.getParameter(ServletConstants.arg_operat_B) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		
		String strMinSendTime = request.getParameter(ServletConstants.arg_min_recharge_time) ;
		String strMaxSendTime = request.getParameter(ServletConstants.arg_max_recharge_time) ;
		
		long startTime = -1 ;
		long endTime = -1 ;
		

		if (operation == null || operator == null || operaA == null || operaB == null 
				|| strPageNo == null || strMinSendTime == null || strMaxSendTime == null )
			return Status.INVALID_ARGUMENT ;
		
		int pageNo = 1 ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
			if (strMinSendTime != null && strMinSendTime.length() > 6)
				startTime = Long.parseLong(strMinSendTime) ;
			if (strMaxSendTime != null && strMaxSendTime.length() > 6)
				endTime = Long.parseLong(strMaxSendTime) ;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
		PageList pageList = Globals.getLoggerList(startTime, endTime, operation, 
				operaA, operaB, null, operator, pageNo) ;
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;

    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>充值时间</td>");
				result.append("<td>操作人</td>");
				result.append("<td>操作类型</td>");
				result.append("<td>参数A</td>");
				result.append("<td>参数B</td>");
				result.append("<td>备注</td>");
			result.append("</tr>");
			LoggerRecordBean loggerRecord = null;
			Timestamp temp = new Timestamp(System.currentTimeMillis()) ;
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				
				loggerRecord = (LoggerRecordBean)pageList.getList().get(i) ; 
				temp.setTime(loggerRecord.getCurTime()) ;
				result.append("<tr>");
				result.append("<td>").append(String.format("%04d-%02d-%02d %02d:%02d", 1900+temp.getYear(),temp.getMonth()+1,temp.getDate(),temp.getHours(),temp.getMinutes())).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOperator()).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOperation()).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOpera_A()).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOpera_B()).append("</td>") ;
				result.append("<td>").append(loggerRecord.getOpera_C()).append("</td>") ;
	            result.append("</tr>");
			}
        result.append("</table>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryLogger(this);"));

		response.getWriter().write(result.toString()) ;

		return Status.OK;		
	}

	public static  void getOperationOptions(StringBuffer sb)
	{
		sb.append("<option value=\"\">全部</option>") ;
		sb.append("<option value=rechargeUser>主账号充值</option>") ;
		sb.append("<option value=rechargeAccount>子账号充值</option>") ;
		sb.append("<option value=mergeAccount>子账号合并</option>") ;
	}
	private Status getQueryLoggerDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=jNice>");
        		result.append("<h3>查询条件</h3>");
        		result.append("<div nowrap>") ;
                        	result.append("<p>");
                        	result.append("<label>操作类型：</label>");
                        	result.append("<select id=operation>");
                        	getOperationOptions(result) ;
                        	result.append("</select>");
                        	result.append("<label>&nbsp;&nbsp;&nbsp;&nbsp;充值时间：</label><input id=rechargeDate type=text class=textDate value=").append(new Date(System.currentTimeMillis())).append(" />") ;
                        	result.append("从&nbsp;&nbsp;<input id=minRechargeTime type=text class=textSmall value=00:00:00 />") ;
                        	result.append("到&nbsp;&nbsp;<input id=maxRechargeTime type=text class=textSmall value=23:59:59 />") ;
                        	result.append("</p>");
                        	result.append("<p>") ;
                        	result.append("<label>参数A：</label><input id=operaA type=text class=textLong maxlength=48/>");                     	
                        	result.append("<label>参数B：</label><input id=operaB type=text class=textLong maxlength=48/>");
                        	result.append("</p>");
                        	result.append("<p>") ;
                        	result.append("<label>操作人：</label><input id=operator type=text class=textMedium maxlength=20/>");
                    		result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"查询\" onclick=\"onQueryLogger();return false;\"/>");
                result.append("</p></div>") ;
        result.append("</form>") ;

		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}

	private Status deleteUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String strUserId = request.getParameter(ServletConstants.arg_user_id) ;
		if (strUserId == null)
			return Status.INVALID_ARGUMENT ;
		
		long userId = -1L ;
		userId = Long.parseLong(strUserId) ;
		UserBean user = Globals.getUserBuffer().getById(userId) ;
		if (Constants.super_user_name.equalsIgnoreCase(user.getUserName()))
			return Status.INVALID_VALUE ;
		
		Status status = mserver.s_deleteUser(userId) ;
		if (status == Status.OK)
			response.getWriter().write(status.toString()) ;
		return status;
	}

	private Status deleteClient(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String strClientId = request.getParameter(ServletConstants.arg_client_id) ;
		if (strClientId == null)
			return Status.INVALID_ARGUMENT ;
		long clientId = Long.parseLong(strClientId) ;
		Status status =  mserver.s_deleteClient(clientId) ;
		if (status == Status.OK)
			response.getWriter().write(status.toString()) ;
		return status ;
	}

	private Status updateClient(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String strClientId = request.getParameter(ServletConstants.arg_client_id) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		String name = request.getParameter(ServletConstants.arg_name) ;
		String phone = request.getParameter(ServletConstants.arg_phone) ;
		
		if(strClientId == null || password == null || name == null || phone == null)
			return Status.INVALID_ARGUMENT ;
			

		long clientId = -1L ;
		try{
			clientId = Long.parseLong(strClientId) ;
		}catch(Exception e)
		{
			return Status.INVALID_VALUE ;
		}
		if (!UserBean.isValidPassword(password))
			return Status.INVALID_VALUE ;
		
		name = java.net.URLDecoder.decode(name,"UTF-8") ;
		Status status = mserver.s_updateClient(clientId, password, name, phone) ;

		if(status == Status.OK)
			response.getWriter().write(Status.OK.toString()) ;
		
		return status;
	}

	private Status querySingleClient(HttpServletRequest request,
			HttpServletResponse response) {
		String strClientId = request.getParameter(ServletConstants.arg_client_id) ;
		if(strClientId == null)
			return Status.INVALID_ARGUMENT ;
		long clientId = Integer.parseInt(strClientId) ;
		ClientBean clientBean =  Globals.getClientBuffer().getClient(clientId) ;
		if(clientBean == null)
			return Status.INVALID_VALUE ;
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<form>");
	     result.append("<fieldset>");
           	result.append("<p><label>客户端:</label><input disabled=disabled class=\"text ui-widget-content ui-corner-all\" id=gameDiscription name=gameDiscription type=text maxlength=10 value=\"").append(clientBean.getClientName()).append("\" /></p>");
               result.append("<p><label>新密码：</label><input class=\"text ui-widget-content ui-corner-all\" id=password type=password maxlength=10 value=\"").append(clientBean.getPassword()).append("\" /></p>");
               result.append("<p><label>新密码确认：</label><input class=\"text ui-widget-content ui-corner-all\" id=passwordConfirm type=password maxlength=10 value=\"").append(clientBean.getPassword()).append("\" /></p>");
               result.append("<p><label>姓名:</label><input class=\"text ui-widget-content ui-corner-all\" id=name type=text maxlength=6 value=\"").append(clientBean.getName()).append("\"/></p>");
               result.append("<p><label>手机号:</label><input class=\"text ui-widget-content ui-corner-all\" id=phone type=text maxlength=16 value=\"").append(clientBean.getPhone()).append("\"/></p>");
               result.append("<input type=\"submit\" value=\"更新\" onclick=\"onUpdateClient(); return false;\"/>");
               result.append("<input id=clientId name=clientId class=ui-button type=hidden value=").append(clientId).append(" />");
           result.append("</fieldset>");
        result.append("</form>");
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}		
		
		return Status.OK;
	}

	private Status createClient(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String clientName = request.getParameter(ServletConstants.arg_client_name) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		String name = request.getParameter(ServletConstants.arg_name) ;
		String phone = request.getParameter(ServletConstants.arg_phone) ;
		if(clientName == null || password == null || name==null || phone == null)
			return Status.INVALID_ARGUMENT ;
		
		if (!UserBean.isValidUserName(clientName) || !UserBean.isValidPassword(password) )
			return Status.INVALID_VALUE ;
		
		StringBuffer result = new StringBuffer(10) ;
		name = java.net.URLDecoder.decode(name,"UTF-8") ;
		Status status = mserver.s_createClient(clientName,password,name,phone,result) ;
		
		if(status == Status.OK)
			response.getWriter().write(result.toString()) ;

		return status;
	}

	private Status getCreateClientDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<form>");
	     result.append("<fieldset>");
               result.append("<p><label>客户端名:</label><input class=\"text ui-widget-content ui-corner-all\" id=ClientName type=text maxlength=20/></p>");
               result.append("<p><label>密码:</label><input class=\"text ui-widget-content ui-corner-all\" id=password type=password maxlength=20/></p>");
               result.append("<p><label>确认密码:</label><input class=\"text ui-widget-content ui-corner-all\" id=passwordConfirm type=password maxlength=20/></p>");
               result.append("<p><label>姓名:</label><input class=\"text ui-widget-content ui-corner-all\" id=name type=text maxlength=6/></p>");
               result.append("<p><label>手机号:</label><input class=\"text ui-widget-content ui-corner-all\" id=phone type=text maxlength=16/></p>");
               result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"新建客户端\" onclick=\"onCreateClient(); return false;\"/>");
           result.append("</fieldset>");
        result.append("</form>");

    	response.setCharacterEncoding("utf8") ;
		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}

	private Status queryAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String account = request.getParameter(ServletConstants.arg_account) ;
		String strMinValidDate = request.getParameter(ServletConstants.arg_min_valid_date);
		String strMaxValidDate = request.getParameter(ServletConstants.arg_max_valid_date);
		String strMinLeftPoint = request.getParameter(ServletConstants.arg_min_left_point) ;
		String strMaxLeftPoint = request.getParameter(ServletConstants.arg_max_left_point) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		
		if (account != null && account.length() > 0 && !AccountBean.isValidFormat(account))
			return Status.INVALID_VALUE ;
		
		long minValidTime = 0 ;
		long maxValidTime = 0 ;
		int minLeftPoint = 0 ;
		int maxLeftPoint = 0 ;
		int pageNo = 1 ;
		try
		{
			if (strMinValidDate != null && strMinValidDate.length() == 10)
				minValidTime = java.sql.Timestamp.valueOf(strMinValidDate+" 00:00:00").getTime() ;
			if (strMaxValidDate != null && strMaxValidDate.length() == 10)
				maxValidTime = java.sql.Timestamp.valueOf(strMaxValidDate+" 23:59:59").getTime() ;
			if (strMinLeftPoint != null && strMinLeftPoint.length() > 0)
				minLeftPoint = Integer.parseInt(strMinLeftPoint) ;
			if (strMaxLeftPoint != null && strMaxLeftPoint.length() > 0)
				maxLeftPoint = Integer.parseInt(strMaxLeftPoint) ;
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
		}
		catch(Exception e)
		{
			return Status.INVALID_VALUE ;
		}
		
		UserBean user = (UserBean) request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		if (user == null)
			return Status.INVALID_ARGUMENT ;
		PageList pageList = Globals.getAccountList(-1L, pageNo,userName, account, minValidTime, maxValidTime, minLeftPoint, maxLeftPoint);
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<h3>子账号列表</h3>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryAccount(this);"));
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>注册码</td>");
				result.append("<td>生成日期/有效期/最后使用日期</td>");
				//result.append("<td>有效期</td>");
				result.append("<td>余额/报错率</td>");
//				result.append("<td>报错率</td>");
				result.append("<td class=\"action\">操作</td>");
			result.append("</tr>");
			AccountBean accountBean ;
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				accountBean = (AccountBean)pageList.getList().get(i) ; 
				result.append(i%2==0?"<tr class=\"odd\" ":"<tr ").append("id=").append(accountBean.getAccount()).append(">");
	                result.append("<td>").append(accountBean.getAccount()).append("</td>");
					result.append("<td>").append(new Date(accountBean.getBirthTime())).append("/")
						.append(new Date(accountBean.getValidTime())).append("/")
						.append(accountBean.getLastTime()>0?new Date(accountBean.getLastTime()):"-").append("</td>");
				//	result.append("<td>").append(new Date(accountBean.getValidTime())).append("</td>");
					//result.append("<td>").append(account.getPoint()).append("</td>");
					result.append("<td>").append(accountBean.getLeftPoint()).append("/")
						.append(accountBean.getSendCount()>0?String.format("%.2f%%", accountBean.getReportCount()*100.0/accountBean.getSendCount()):"-").append("</td>");
//					result.append("<td>").append(accountBean.getSendCount()>0?String.format("%.2f%%", accountBean.getReportCount()*100.0/accountBean.getSendCount()):"-").append("</td>");
					if (accountBean != null && !accountBean.isDeleted())
					{
						result.append("<td class=\"action\"><a href=\"#\" class=\"edit\" onclick=\"querySingleAccount('"+accountBean.getAccount()+"'); return false;\">详细</a>");
						if (accountBean.isFreeze())
							result.append("<a href=\"#\" class=\"delete\" onclick=\"unfreezeAccount('"+accountBean.getAccount()+"'); return false;\">解冻</a></td>");
						else
							result.append("<a href=\"#\" class=\"delete\" onclick=\"freezeAccount('"+accountBean.getAccount()+"'); return false;\">冻结</a></td>");
					}
					else
					{
						result.append("<td class=\"action\">已删除</td>");
					}
	            result.append("</tr>");
			}
        result.append("</table>");
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;		
	}
	/**
	 * 冻结子账号
	 * 
	 * */
	private Status freezeAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{

		String account = request.getParameter(ServletConstants.arg_account) ;
		UserBean userBean = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		Status status = mserver.s_freezeAccount(userBean,account);
		if (status == Status.OK)
		{
			response.getWriter().write(status.statusCode.toString()) ;
		}
		return status;
	}
	/**
	 * 解冻子账号
	 * 
	 * */
	private Status unfreezeAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		UserBean userBean = (UserBean)request.getSession().getAttribute(ServletConstants.s_attr_user) ;
		Status status = mserver.s_unfreezeAccount(userBean,account);
		if (status == Status.OK)
		{
			response.getWriter().write(status.statusCode.toString()) ;
		}
		return status;
	}
	private Status queryUser(HttpServletRequest request,
			HttpServletResponse response) {
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		
		int pageNo = 1 ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
		PageList pageList = Globals.getUserList(pageNo,userName);
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<h3>用户列表</h3>");
		
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>ID/用户名</td>");
//				result.append("<td>用户名</td>");
				result.append("<td>总点数/剩余点数/返点数</td>");
				result.append("<td>返点比率</td>");
				result.append("<td>注册时间</td>");
				result.append("<td>QQ</td>");
//				result.append("<td>Email</td>");
				result.append("<td class=\"action\">操作</td>");
			result.append("</tr>");
			UserBean user ;
		
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				user = (UserBean)pageList.getList().get(i) ; 
				result.append("<tr id=").append(user.getUserId()).append(">");
					result.append("<td>").append(user.getUserId()).append("/").append(user.getUserName()).append("</td>");
//					result.append("<td>").append(user.getUserName()).append("</td>");
					result.append("<td>").append(user.getPoint()).append("/").append(user.getLeftPoint())
					.append("/").append((String.format("%.2f",user.getReturnPoint()))).append("</td>");
					result.append("<td>").append((String.format("%.2f",user.getReturnRatio()))).append("</td>");
//					result.append("<td>").append(gameType.getUsedPoint()).append("</td>");
					result.append("<td>").append(new Date(user.getBirthTime())).append("</td>");
					result.append("<td>").append(user.getQQ()).append("</td>");
//					result.append("<td>").append(gameType.getEmail()).append("</td>");
					if (user.getUserName().equalsIgnoreCase(Constants.super_user_name))
						result.append("<td class=\"action\">-</td>") ;
					else
					{
						result.append("<td class=\"action\">")
					
							.append("<a href=\"\" class=edit onclick=\"onEditUser(").append(user.getUserId()).append(",").append(String.format("%.3f",user.getReturnRatio()))
							.append("); return false\">编辑</a>").append("<a href=\"\" class=\"delete\" onclick=\"onDeleteUser(").append(user.getUserId())
						.append("); return false;\">删除</a>");
						if (user.isFreeze())
							result.append("<a href=\"#\" class=\"delete\" onclick=\"unfreezeUser('"+user.getUserName()+"'); return false;\">解冻</a></td>");
						else
							result.append("<a href=\"#\" class=\"delete\" onclick=\"freezeUser('"+user.getUserName()+"'); return false;\">冻结</a></td>");
						
						result.append("</td>") ;
					}
	            result.append("</tr>");
			}

        result.append("</table>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryUser();"));
        
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;	
	}

	private Status queryGameType(HttpServletRequest request,
			HttpServletResponse response) 
	{
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		
		int pageNo = 1 ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
		PageList pageList = Globals.getGameTypeList(pageNo);
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<h3>项目类型</h3>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryGameType();"));
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>项目编号</td>");
				result.append("<td>项目类型</td>");
				result.append("<td>答案类型/长度</td>");
				result.append("<td>超时时间</td>");
				result.append("<td>点数/工人点数</td>");
				result.append("<td>转发/难度系数</td>");
//				result.append("<td>难度</td>");
				result.append("<td class=\"action\">操作</td>");
			result.append("</tr>");
			GameTypeBean gameType ;
		
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				gameType = (GameTypeBean)pageList.getList().get(i) ; 
				result.append("<tr id=").append(gameType.getGameType()).append(">");
					result.append("<td>").append(gameType.getGameType()).append("</td>");
					result.append("<td>").append(gameType.getGameDescription()).append("</td>");
					result.append("<td>").append(gameType.getAnswerTypeDes()).append("/").append(gameType.getAnswerLen()).append("</td>");
//					result.append("<td>").append(message.getAnswerLen()).append("</td>");
					result.append("<td>").append(gameType.getMinInterval()).append("</td>");
					result.append("<td>").append(gameType.getPoint()).append("/").append(gameType.getPoint_worker()).append("</td>");
					result.append("<td>").append(gameType.getTransOn().getTransDes()).append("/").append(String.format("%.3f",gameType.getDifficulty())).append("</td>");
//					result.append("<td>").append(String.format("%.3f",gameType.getDifficulty())).append("</td>");
					result.append("<td class=\"action\"><a href=\"#\" class=\"edit\" onclick=\"onEditGameType(").append(gameType.getGameType())
						.append("); return false;\">编辑</a><a href=\"\" class=\"delete\" onclick=\"onDeleteGameType(").append(gameType.getGameType())
						.append("); return false;\">删除</a></td>");
	            result.append("</tr>");
			}
        result.append("</table>");
        result.append("<input type=button class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" onclick=\"openCreateGameTypeDlg();\" value=\"新建项目类型\"/>") ;
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;	
	}

	private Status getQueryAccountDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=jNice>");
		result.append("<h3>查询条件</h3>");
		result.append("<div nowrap>") ;
			result.append("<p><label>有效期：</label>");
	        result.append("<select id=min_validDate_year>");
			result.append("<option value=\"\" selected=selected>年</option><option value=2012>2012</option><option value=2013>2013</option><option value=2014>2014</option><option value=2015>2015</option><option value=2016>2016</option><option value=2018>2018</option><option value=2020>2020</option><option value=2100>2100</option>");
			result.append("</select>");
	        result.append("<select id=min_validDate_month>");
			result.append("<option value=\"\">月</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option><option>11</option><option>12</option>");
			result.append("</select>");
	        result.append("<select id=min_validDate_day>");
			result.append("<option value=\"\">日</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option>");
			result.append("<option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option>");
			result.append("<option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option><option>31</option>");
			result.append("</select>至");
	        result.append("<select id=max_validDate_year>");
			result.append("<option value=\"\">年</option><option>2012</option><option>2013</option><option>2014</option><option>2015</option><option>2016</option><option>2018</option><option>2020</option><option>2100</option>");
			result.append("</select>");
	        result.append("<select id=max_validDate_month>");
			result.append("<option value=\"\">月</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option><option>11</option><option>12</option>");
			result.append("</select>");
	        result.append("<select id=max_validDate_day>");
			result.append("<option value=\"\">日</option><option>01</option><option>02</option><option>03</option><option>04</option><option>05</option><option>06</option><option>07</option><option>08</option><option>09</option><option>10</option>");
			result.append("<option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option>");
			result.append("<option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option><option>31</option>");
			result.append("</select>");
	        result.append("<label>&nbsp;&nbsp;&nbsp;余额：</label><input id=min_left_point type=number class=textSmall maxlength=8/>至<input id=max_left_point type=number class=textSmall maxlength=8/>");
	        result.append("</p>") ;
	    	result.append("<p><label>用&nbsp;户&nbsp;名&nbsp;&nbsp;：</label><input id=userName type=text class=textMedium maxlength=20/>");
	    	result.append("<label>子账号：</label><input id=account type=text class=textLong maxlength=48/>");
//	    	result.append("</p>");
//	    	result.append("<p>");
			result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=submit value=提交查询 onclick=\"onQueryAccount();return false;\"/>");
			result.append("</p>");
        result.append("</div>");
        result.append("</form>");
	    
		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}

	private Status getQueryUserDlg(HttpServletRequest request,
			HttpServletResponse response) 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>查询条件</h3>");
        		result.append("<div nowrap>") ;
                        	result.append("<p>");
                        	result.append("<label>用户名</label><input id=userName type=text class=textMedium maxlength=20/>");
                    		result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"查询\" onclick=\"onQueryUser();return false;\"/>");
                result.append("</p></div>") ;
        result.append("</form>") ;
	    try
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;
	}

	private Status getQueryClientDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>查询条件</h3>");
        		result.append("<div nowrap>") ;
                        	result.append("<p>");
                        	result.append("<label>客户端</label><input id=clientName type=text class=textMedium maxlength=20/>");
                    		result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"查询\" onclick=\"onQueryClient();return false;\"/>");
                result.append("</p></div>") ;
        result.append("</form>") ;

		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}
	
	private Status getStasticClientDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>查询条件</h3>");
        		result.append("<div nowrap>") ;
                        	result.append("<p>");
                        	result.append("<label>客户端</label><input id=clientName type=text class=textMedium maxlength=20/>");
                        	result.append("<label>统计日期：</label><input id=minStasticTime type=text class=textDate value=").append(new Date(System.currentTimeMillis())).append(" />") ;
//                        	result.append("从&nbsp;&nbsp;<input id=minStasticTime type=text class=textSmall value=00:00:00 />") ;
                        	result.append("到&nbsp;&nbsp;<input id=maxStasticTime type=text class=textDate value=").append(new Date(System.currentTimeMillis())).append(" />") ;
                    		result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"查询\" onclick=\"onStasticClient();return false;\"/>");
                result.append("</p></div>") ;
        result.append("</form>") ;

		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}
	
	/**
	 * 目前仅支持全HTTP方式
	 * 
	 * */
	private void getModeOptions(StringBuffer result)
	{
//		result.append("<option ").append(Constants.protocol.equalsIgnoreCase("HTTP_UDP")?"selected=selected":"").append(">HTTP_UDP</option>");
//		result.append("<option ").append(Constants.protocol.equalsIgnoreCase("TCP_UDP")?"selected=selected":"").append(">TCP_UDP</option>");
		result.append("<option ").append(Constants.protocol.equalsIgnoreCase("HTTP_ALL")?"selected=selected":"").append(">HTTP_ALL</option>");
	}
	
	private Status getChangeModeDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<form>");
		result.append("<h3>服务器设置</h3>");
	     result.append("<fieldset>");
	     result.append("<p><label>公开Key:</label>");
   	   			result.append("<input type=text class=textMedium id=key value=").append(Constants.key).append(" ></input></p>") ;
   	   			result.append("<p><label>本地队列:</label>");
	     	   result.append("<input type=text class=text-small id=maxMsgLocal value=").append(Constants.max_msg_local).append(" ></input></p>") ;
	     	   result.append("<p><label>转发阈值:</label>");
	     	   result.append("<input type=text class=text-small id=transThreshold value=").append(Constants.trans_threshold).append(" ></input></p>") ;
	     	  result.append("<p><label>点数比率00-08:</label>");
	     	   result.append("<input type=text class=text-small id=pointRatio0008 value=").append(Constants.point_ratio_00_08).append(" ></input></p>") ;
	     	  result.append("<p><label>点数比率08-16:</label>");
	     	   result.append("<input type=text class=text-small id=pointRatio0816 value=").append(Constants.point_ratio_08_16).append(" ></input></p>") ;
	     	  result.append("<p><label>点数比率16-24:</label>");
	     	   result.append("<input type=text class=text-small id=pointRatio1624 value=").append(Constants.point_ratio_16_24).append(" ></input></p>") ;
//	     	   result.append("<p><label>插件模式:</label>");
//               result.append("<select class=\"text ui-widget-content ui-corner-all\" id=mode name=mode>");
//               getModeOptions(result) ;
//               result.append("</select></p>");
               result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"更新服务器设置\" onclick=\"onChangeMode(); return false;\"/>");
           result.append("</fieldset>");
        result.append("</form>");

		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}
	
	private String updateSysInfo(String sysInfoServerURL,String ip_sysInfo,int portSysInfo, String hostURL,
			String protocol, int portTcp, int portUdp, int portHttp,
			String ip_ctc, String ip_cucc, String ip_cmcc, String ip_other,
			String userName, String password) throws IOException
	{
		String message = String.format("%s#%s#%d#%d#%s#%s#%s#%s#%d#%s#%s", "updateSysInfo",
				protocol,portTcp,portUdp,
				ip_ctc,ip_cucc,ip_cmcc,ip_other,
				portHttp,hostURL,userName) ;
		System.out.println("Change mode for "+sysInfoServerURL+"\n"+ message) ;
        
		String recvStr = null ;
        
	    String url = sysInfoServerURL+"/sysInfo?actionType=updateSysInfo" ;
	    url += "&protocol="+protocol+"&portTcp="+portTcp+"&portUdp="+portUdp+"&portHttp="+portHttp
	    	+"&ipCtc="+ip_ctc+"&ipCucc="+ip_cucc+"&ipCmcc="+ip_cmcc+"&ipOther="+ip_other+"&hostURL="+hostURL
	    	+"&userName="+userName+"&password="+password+"&_="+System.currentTimeMillis();
        GetMethod httpGet = new GetMethod(url) ;
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 设置连接时间
        try
        {
            int status = client.executeMethod(httpGet);
            if (status != HttpStatus.SC_OK) 
            {
                System.out.println("服务器访问失败") ;
                recvStr = null ;
            }
            else if (status == HttpStatus.SC_OK) 
            {   
            	recvStr = httpGet.getResponseBodyAsString() ;
            } 
        }
        catch (IOException e)
        {
            e.printStackTrace();
            System.out.println("网络异常") ;
            recvStr = null ;
        }
        httpGet.releaseConnection() ;
        
        if(!"0".equalsIgnoreCase(recvStr))
        {
        	logger.error("更新服务器设置失败"+sysInfoServerURL);
        	return null ;
        }
        
		return recvStr ;
	}
	private Status getSwitchServerDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException
	{
		
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<form>");
		result.append("<h3>服务器设置</h3>");
	    result.append("<fieldset>");
	    result.append("<p><label>代理服务器IP:</label>")
	    	.append("电信：").append(Constants.localIP_CMCC)
		    .append("<br>联通：").append(Constants.localIP_CUCC)
		    .append("<br>铁通：").append(Constants.localIP_CTC)
		    .append("<br>其他：").append(Constants.localIP_OTHER)
		    .append("<br>端口：").append(Constants.portHttp).append("</p>"); 	   
	    result.append("<p><label>系统信息服务器IP:</label>")
	    .append("主服务器：").append(Constants.ip_sysinfo)
	    .append("<br>备用服务器：").append(Constants.ip_sysinfo_backup);
	    if(Constants.needUpdateOldSysInfoServer)
	    {
	    	result.append("<br>旧主服务器：").append(Constants.ip_sysinfo_old_1)
		    	.append("<br>旧备用服务器：").append(Constants.ip_sysinfo_old_2);
	    }
	    result.append("</p>");
	    result.append("<p><label>插件模式:</label>");
	    result.append("<select class=\"text ui-widget-content ui-corner-all\" id=mode name=mode>");
	    getModeOptions(result) ;
	    result.append("</select></p>");
	    result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"切换服务器\" onclick=\"onSwitchServer(); return false;\"/>");
	    result.append("</fieldset>");
        result.append("</form>");

		response.getWriter().write(result.toString()) ;
		
		return Status.OK ;
	}
	private Status switchServer(HttpServletRequest request,
			HttpServletResponse response) throws IOException
	{
		String mode = request.getParameter(ServletConstants.arg_mode) ;
		try 
		{			        
			// 主系统信息查询服务器
			String sysInfoServerURL = "http://"+ Constants.ip_sysinfo+":"+Constants.portSysInfoHttp ;
			String recvStr = updateSysInfo(sysInfoServerURL, Constants.ip_sysinfo, Constants.portSysInfo,
					Constants.hostURL, mode, Constants.portSendFile, Constants.portGetAnswer,
					Constants.portHttp, Constants.localIP_CTC, Constants.localIP_CUCC, Constants.localIP_CMCC,
					Constants.localIP_OTHER, Constants.super_user_name, Constants.super_password) ;
			if (!"0".equalsIgnoreCase(recvStr))
				return Status.OTHER_ERROR ;
			// 备用系统信息查询服务器
			sysInfoServerURL = "http://"+ Constants.ip_sysinfo_backup+":"+Constants.portSysInfoHttp  ;
			recvStr = updateSysInfo(sysInfoServerURL, Constants.ip_sysinfo_backup, Constants.portSysInfo,
					Constants.hostURL, mode, Constants.portSendFile, Constants.portGetAnswer,
					Constants.portHttp, Constants.localIP_CTC, Constants.localIP_CUCC, Constants.localIP_CMCC,
					Constants.localIP_OTHER, Constants.super_user_name, Constants.super_password) ;
			if (!"0".equalsIgnoreCase(recvStr))
				return Status.OTHER_ERROR ;
			
			if (Constants.needUpdateOldSysInfoServer)
			{
				// 主系统信息查询服务器
//				sysInfoServerURL = "http://"+ Constants.ip_sysinfo_old_1+":"+Constants.portSysInfoHttp ;
//				recvStr = updateSysInfo(sysInfoServerURL, Constants.ip_sysinfo, Constants.portSysInfo,
//						Constants.hostURL, mode, Constants.portSendFile, Constants.portGetAnswer,
//						Constants.portHttp, Constants.localIP_CTC, Constants.localIP_CUCC, Constants.localIP_CMCC,
//						Constants.localIP_OTHER, Constants.super_user_name, Constants.super_password) ;
//				if (!"0".equalsIgnoreCase(recvStr))
//					return Status.OTHER_ERROR ;
				// 备用系统信息查询服务器
				sysInfoServerURL = "http://"+ Constants.ip_sysinfo_old_2+":"+Constants.portSysInfoHttp  ;
				recvStr = updateSysInfo(sysInfoServerURL, Constants.ip_sysinfo_backup, Constants.portSysInfo,
						Constants.hostURL, mode, Constants.portSendFile, Constants.portGetAnswer,
						Constants.portHttp, Constants.localIP_CTC, Constants.localIP_CUCC, Constants.localIP_CMCC,
						Constants.localIP_OTHER, Constants.super_user_name, Constants.super_password) ;
				if (!"0".equalsIgnoreCase(recvStr))
					return Status.OTHER_ERROR ;				
			}
			
		} catch (IOException e) {
			e.printStackTrace();
			return Status.NETWORK_ERROR ;
		}
		
        // 重新生成msgID序列号，防止切换时主键冲突
        Globals.regetIDGenerator() ;	
        
		Constants.protocol = mode ;
        
		
		response.getWriter().write(Status.OK.toString()) ;
		return Status.OK ;
	}

	/**
	 * 
	 * 切换服务器
	 * 
	 * 
	 * */
	private Status changeMode(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		Status status = Status.OK ;
		String key = request.getParameter(ServletConstants.arg_key);
		
		String maxMsgLocal = request.getParameter(ServletConstants.arg_max_msg_local) ;
		String strTransThreshold = request.getParameter(ServletConstants.arg_trans_threshold) ;
		String strPointRatio0008 = request.getParameter(ServletConstants.arg_point_ratio_0008) ;
		String strPointRatio0816 = request.getParameter(ServletConstants.arg_point_ratio_0816) ;
		String strPointRatio1624 = request.getParameter(ServletConstants.arg_point_ratio_1624) ;
		if( maxMsgLocal == null || strTransThreshold == null ||
				strPointRatio0008 == null || strPointRatio0816 == null || strPointRatio1624 == null || key == null)
			return Status.INVALID_ARGUMENT ;
		
		int maxMsg = Integer.parseInt(maxMsgLocal) ;
		if (maxMsg <=0 || maxMsg > 25)
			return Status.INVALID_VALUE ;
		
		int transThreshold = Integer.parseInt(strTransThreshold) ;
		if (transThreshold < 0 || transThreshold > 10000)
			return Status.INVALID_VALUE ;
		
		double ratio0008 = Double.parseDouble(strPointRatio0008) ;
		double ratio0816 = Double.parseDouble(strPointRatio0816) ;
		double ratio1624 = Double.parseDouble(strPointRatio1624) ;
		
		Constants.max_msg_local = maxMsg ;
		Constants.trans_threshold = transThreshold ;
		Constants.point_ratio_00_08 = ratio0008 ;
		Constants.point_ratio_08_16 = ratio0816 ;
		Constants.point_ratio_16_24 = ratio1624 ;

		Constants.key = key ;
		
		if (status.isOK())
			response.getWriter().write(status.toString()) ;
		
		return status;
	}

	private Status queryAnswerRecord(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		String clientName = request.getParameter(ServletConstants.arg_client_name) ;
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String ip = request.getParameter(ServletConstants.arg_ip) ;
		String strGameType = request.getParameter(ServletConstants.arg_game_type) ;
		String strStatus = request.getParameter(ServletConstants.arg_status) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		String strMsgId = request.getParameter(ServletConstants.arg_msg_id) ;
		String strMinSendTime = request.getParameter(ServletConstants.arg_min_send_time) ;
		String strMaxSendTime = request.getParameter(ServletConstants.arg_max_send_time) ;
		String returnUser = request.getParameter(ServletConstants.arg_return_user) ;
		
		int gameType = Integer.MIN_VALUE, status = Integer.MIN_VALUE ;
		long msgId = Long.MIN_VALUE ;
		long minSendTime = -1 ;
		long maxSendTime = -1 ;
		
//		if (account != null && account.length() > 0 && !AccountBean.isValidAccount(account))
//			return Status.INVALID_VALUE ;
		if (account == null || clientName == null || userName == null || ip == null || strGameType == null
				|| strStatus == null || strPageNo == null || strMsgId == null || strMinSendTime == null || strMaxSendTime == null)
			return Status.INVALID_ARGUMENT ;
		
		int pageNo = 1 ;
		long returnUserId = -1L ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
			if (strGameType != null && strGameType.length() > 0)
				gameType = Integer.parseInt(strGameType) ;
			if (strStatus != null && strStatus.length() > 0)
				status = Integer.parseInt(strStatus) ;
			if (strMsgId != null && strMsgId.length() > 0)
				msgId = Long.parseLong(strMsgId) ;
			if (strMinSendTime != null && strMinSendTime.length() > 6)
				minSendTime = Long.parseLong(strMinSendTime) ;
			if (strMaxSendTime != null && strMaxSendTime.length() > 6)
				maxSendTime = Long.parseLong(strMaxSendTime) ;
			if (returnUser != null && returnUser.length() > 0)
			{
				UserBean user = Globals.getUserBuffer().getByUserName(returnUser) ;
				if (user != null)
					returnUserId = user.getUserId() ;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
//		PageList pageList = Globals.getAnswerRecordList(pageNo, account, filter);
		PageList pageList = Globals.getAnswerRecordListForSuper(pageNo,
							msgId,account, clientName, gameType, status, ip, userName,
							minSendTime,maxSendTime,returnUserId) ;
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;
//		result.append("<h3>答题记录列表</h3>");

    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>用户名/题号/客户端</td>");
				result.append("<td>发送时间/IP/处理速度</td>");
				result.append("<td>类型/状态/答案</td>");
				result.append("<td>返点账号/扣点</td>");
				result.append("<td class=action>子账号</td>");
				result.append("<td class=action>查看</td>");
			result.append("</tr>");
			MessageBean message ;
			Timestamp temp = new Timestamp(System.currentTimeMillis()) ;
		
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				message = (MessageBean)pageList.getList().get(i) ; 
				temp.setTime(message.getReceiveTime()) ;
				ClientBean client = Globals.getClientBuffer().getClient(message.getClientId());
				result.append("<tr>");
	                UserBean user = Globals.getUserBuffer().getById(message.getUserId()) ;
	                AccountBean accountBean = Globals.getAccountBuffer().get(message.getAccountId()) ;
	            
	                result.append("<td>").append(user.getUserName())
	                	.append("/").append(message.getId())
	                	.append("/").append(client==null?"-":client.getClientName())
	                	.append("</td>");
					result.append("<td>")
					.append(String.format("%02d-%02d %02d:%02d:%02d",temp.getMonth()+1,temp.getDate(),temp.getHours(),temp.getMinutes(),temp.getSeconds()));
					result.append("/").append(message.getIp()).append("/") ;
					if(message.getAnswerTime()>0)
						result.append((message.getAnswerTime()-message.getReceiveTime())/1000) ;
					else
						result.append("-");
					result.append("</td>");
					result.append("<td>")
					.append(message.getGameType())
						.append("/").append(message.getMessageStatus())	
						.append("/").append(message.getAnswer()==null?"-":message.getAnswer())
						.append("</td>");
					UserBean returnUserBean = Globals.getUserBuffer().getById(message.getReturnUserId()) ;
					result.append("<td>").append(returnUserBean==null?"-":returnUserBean.getUserName()).append("/").append(message.getUPoint()).append("</td>") ;
					result.append("<td class=action>");
					if (accountBean != null)
					 result.append("<a href=\"#\" class=\"view\" onclick=\"showDialog('")
						.append(accountBean.getAccount()).append("','子账号'); return false;\">")
						.append(message.getAccountId()).append("</a>");
					else
						result.append(message.getAccountId()) ;
					result.append("</td>");
//					result.append("<td>").append(accountBean.getAccount()).append("</td>");
					result.append("<td class=action>") ;
					if (message.getContent() == null)
						result.append("-") ;
					else
					{
						String path = Globals.getUploadDirAbsolutePath()+message.getId() ;
						File file = new File(path);
						if(!file.exists())
						{	
							file.createNewFile() ;
							FileOutputStream fos = new FileOutputStream(file);
							fos.write(message.getContent()) ;
							fos.close() ;
						}
						path = Globals.getUploadRelativePath()+message.getId();
						result.append("<a href=\"#\" class=\"view\" onclick=\"onShowImage('").append(path)
						.append("'); return false;\">原图</a>") ;
					}
					result.append("</td>");

				
	            result.append("</tr>");
			}
        result.append("</table>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryAnswerRecord(this);"));
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;		
	}

	public static void getMessageStatuOptions(StringBuffer result)
	{
		MessageStatus[] values = MessageStatus.values() ; 
		result.append("<option value=\"\">全部</option>") ;
		for(int i = 0 ; i < values.length ; i++)
			result.append("<option value=").append(values[i].status).append(">")
			.append(values[i].description).append("</option>") ;
		return ;
	}
	
	private Status getQueryAnswerRecordDlg(HttpServletRequest request,
			HttpServletResponse response) 
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>查询条件</h3>");
        		result.append("<div nowrap>") ;
                        	result.append("<p>");
                        	result.append("<label>客&nbsp;户&nbsp;端&nbsp;&nbsp;：</label><input id=clientName type=text class=textMedium maxlength=20/>");
                        	result.append("<label>题&nbsp;&nbsp;&nbsp;&nbsp;号：</label><input id=msgId type=text class=textSmall maxlength=48/>");
                          	result.append("<label>IP：</label><input id=ip type=text class=textMedium maxlength=15/>");
                        	result.append("<label>状态：</label><select id=status>");
                        	getMessageStatuOptions(result) ;
                        	result.append("</select></p>");
                        	result.append("<p><label>用&nbsp;户&nbsp;名&nbsp;&nbsp;：</label><input id=userName type=text class=textMedium maxlength=20/>");
                        	result.append("<label>子账号：</label><input id=account type=text class=textLong maxlength=48/>");
                        	result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"提交查询\" onclick=\"onQueryAnswerRecord();return false;\"/>");
                        	result.append("</p><p>");
                        	result.append("<label>返点用户：</label><input id=returnUser type=text class=textMedium maxlength=20/>");
                        	result.append("<label>项目类型：</label><input id=gameType type=text class=textSmall maxlength=4/>");
                        	result.append("<label>发送时间：</label><input id=sendDate type=text class=textDate value=").append(new Date(System.currentTimeMillis())).append(" />") ;
                        	result.append("从&nbsp;&nbsp;<input id=minSendTime type=text class=textSmall value=00:00:00 />") ;
                        	result.append("到&nbsp;&nbsp;<input id=maxSendTime type=text class=textSmall value=23:59:59 />") ;
                    		result.append("</p>");
                result.append("</div>") ;
        result.append("</form>") ;
	    try
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;
	}
	private Status querySingleAccount(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		if (account == null)
			return Status.INVALID_ARGUMENT ;
		AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
		if (accountBean  == null || accountBean.isDeleted())
			return Status.INVALID_VALUE ;
		
		response.getWriter().write(accountBean.toString()) ;

		return Status.OK;
	}
	private Status querySingleGameType(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String strGameType = request.getParameter(ServletConstants.arg_game_type) ;
		if(strGameType == null)
			return Status.INVALID_ARGUMENT ;
		int gameType = Integer.parseInt(strGameType) ;
		GameTypeBean gameTypeBean =  Globals.getGameTypeBuffer().get(gameType);
		if(gameTypeBean == null)
			return Status.INVALID_VALUE ;
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<form>");
	     result.append("<fieldset>");
           	result.append("<p><label>项目描述:</label><input class=\"text ui-widget-content ui-corner-all\" id=gameDiscription name=gameDiscription type=\"text\" maxlength=10 value=\"").append(gameTypeBean.getGameDescription()).append("\" /></p>");
               result.append("<p><label>答案类型:</label>");
               result.append("<select class=\"text ui-widget-content ui-corner-all\" id=answerType name=answerType>");
               getAnswerTypeOptions(result,gameTypeBean.getAnswerType()) ;
               result.append("</select></p>");
               result.append("<p><label>答案长度:</label><input class=\"text ui-widget-content ui-corner-all\" id=answerLen name=answerLen type=\"text\" maxlength=2 value=").append(gameTypeBean.getAnswerLen()).append(" /></p>");
               result.append("<p><label>超时时间:</label><input class=\"text ui-widget-content ui-corner-all\" id=interval name=interval type=\"text\" maxlength=4 value=").append(gameTypeBean.getMinInterval()).append(" /></p>");
               result.append("<p><label>点&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;数:</label><input class=\"text ui-widget-content ui-corner-all\" id=point name=point type=\"text\" maxlength=3 value=").append(gameTypeBean.getPoint()).append(" /></p>");
               result.append("<p><label>工人点数:</label><input class=\"text ui-widget-content ui-corner-all\" id=pointWorker name=pointWorker type=\"text\" maxlength=5 value=").append(gameTypeBean.getPoint_worker()).append(" /></p>");
               result.append("<p><label>难度:</label><input class=\"text ui-widget-content ui-corner-all\" id=difficulty name=difficulty type=\"text\" maxlength=5 value=").append(String.format("%.3f", gameTypeBean.getDifficulty())).append(" /></p>");
               result.append("<p><label>是否转发:</label>");
               result.append("<select class=\"text ui-widget-content ui-corner-all\" id=transOn name=transOn>");
               getTransOptions(result,gameTypeBean.getTransOn().getTransCode()) ;
//               if (gameTypeBean.isTransOn())
//            	   result.append("<option value=1 selected=selected>是</option><option value=0>否</option>") ;
//               else
//            	   result.append("<option value=1 >是</option><option value=0 selected=selected>否</option>") ;
               result.append("</select></p>");
               result.append("<input type=submit value=\"更新\" onclick=\"onUpdateGameType(); return false;\"/>");
               result.append("<input id=gameType name=gameType type=hidden value=").append(gameType).append(" />");
           result.append("</fieldset>");
        result.append("</form>");

		response.getWriter().write(result.toString()) ;
		
		return Status.OK;
	}

	private void getAnswerTypeOptions(StringBuffer result, int value)
	{
		AnswerType[] values = AnswerType.values() ;
		//result.append("<option value=\"\">全部</option>") ;
		for(int i = 0 ; i < values.length ; i++)
			result.append("<option value=").append(values[i].type).append(values[i].type==value?" selected=selected ":"").append(">")
				.append(values[i].getDescription()).append("</option>");
	}
	
	private void getTransOptions(StringBuffer result, int transOn)
	{
//		result.append("<option value=1 ").append(transOn==1?"selected=selected":"")
//			.append(">微锐</option><option value=2 ").append(transOn==2?"selected=selected":"")
//			.append(" >UU/联众</option><option value=0 ").append(transOn==0?"selected=selected":"")
//			.append(" >否</option>") ;

		TransType[] values = TransType.values() ; 
//		result.append("<option value=\"\">全部</option>") ;
		for(int i = 0 ; i < values.length ; i++)
			result.append("<option value=").append(values[i].getTransCode()).append(transOn==values[i].getTransCode()?" selected=selected":"").append(" >")
			.append(values[i].getTransDes()).append("</option>") ;
		return ;
		
	}
	private Status getCreateGameTypeDlg(HttpServletRequest request,
			HttpServletResponse response) 
	{
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<form>");
	     result.append("<fieldset>");
           	result.append("<p><label>项目描述:</label><input class=\"text ui-widget-content ui-corner-all\" id=gameDiscription name=gameDiscription type=\"text\" maxlength=32/></p>");
               result.append("<p><label>答案类型:</label>");
               result.append("<select class=\"text ui-widget-content ui-corner-all\" id=answerType name=answerType>");
               getAnswerTypeOptions(result,-1) ;
               result.append("</select></p>");
               result.append("<p><label>答案长度:</label><input class=\"text ui-widget-content ui-corner-all\" id=answerLen name=answerLen type=\"text\" maxlength=2/></p>");
               result.append("<p><label>超时时间:</label><input class=\"text ui-widget-content ui-corner-all\" id=interval name=interval type=\"text\" maxlength=4/></p>");
               result.append("<p><label>点&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;数:</label><input class=\"text ui-widget-content ui-corner-all\" id=point name=point type=\"text\" maxlength=3/></p>");
               result.append("<p><label>工人点数:</label><input class=\"text ui-widget-content ui-corner-all\" id=pointWorker name=pointWorker type=\"text\" maxlength=5/></p>");
               result.append("<p><label>是否转发:</label>");
               result.append("<select class=\"text ui-widget-content ui-corner-all\" id=transOn name=transOn>");
               getTransOptions(result,1) ;
               result.append("</select></p>");
               result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"新建项目类型\" onclick=\"onCreateGameType(); return false;\"/>");
//               result.append("<input type=\"button\" value=\"取消\" onclick=\"closeDialog();\"/>");
           result.append("</fieldset>");
        result.append("</form>");
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;
	}

//	private Status getUpdateGameTypeDlg(HttpServletRequest request,
//			HttpServletResponse response) 
//	{
//		return null;
//	}

	private Status deleteGameType(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String strGameType = request.getParameter(ServletConstants.arg_game_type) ;
		if(strGameType == null)
			return Status.INVALID_ARGUMENT ;
		int gameType = Integer.parseInt(strGameType) ;
		Status status = mserver.s_deleteGameType(gameType) ;
		
		if(status == Status.OK)
			response.getWriter().write(Status.OK.toString()) ;

		return status;
	}

	private Status createGameType(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String gameDescription = request.getParameter(ServletConstants.arg_game_description) ;
		String strAnswerType = request.getParameter(ServletConstants.arg_answer_type) ;
		String strAnswerLen = request.getParameter(ServletConstants.arg_answer_len) ;
		String strPoint = request.getParameter(ServletConstants.arg_point) ;
		String strPointWorker = request.getParameter(ServletConstants.arg_point_worker) ;
		String strInterval = request.getParameter(ServletConstants.arg_interval) ;
		String strTransOn = request.getParameter(ServletConstants.arg_trans_on) ;
		String strDifficulty = request.getParameter(ServletConstants.arg_difficulty) ;
		if(gameDescription == null || strAnswerType == null || strAnswerLen == null
				|| strPoint == null || strPointWorker == null || strInterval == null 
				|| strTransOn == null  || strDifficulty == null)
			return Status.INVALID_ARGUMENT ;
		
		int answerType = 0 ;
		int answerLen = 0 ;
		int point = 0 ;
		double pointWorker = 0 ;
		int interval = 0 ;
		int transOn = 1 ;
		double difficulty = 1.0f ;
		try{
			gameDescription = java.net.URLDecoder.decode(gameDescription,"UTF-8") ;
			answerType = Integer.parseInt(strAnswerType) ;
			answerLen = Integer.parseInt(strAnswerLen) ;
			point = Integer.parseInt(strPoint) ;
			pointWorker = Double.parseDouble(strPointWorker) ;
			interval = Integer.parseInt(strInterval) ;
			transOn = Integer.parseInt(strTransOn) ;
			difficulty = Double.parseDouble(strDifficulty) ;
		}catch(Exception e)
		{
			return Status.INVALID_VALUE ;
		}
		if(gameDescription.length() > 10 || gameDescription.indexOf('"')>=0
				|| gameDescription.indexOf('\'')>=0)
			return Status.INVALID_VALUE ;
		
		StringBuffer result = new StringBuffer(4) ;
		Status status = mserver.s_createGameType(gameDescription,answerType,answerLen,interval,point,pointWorker,transOn,difficulty,result) ;
		if(status == Status.OK)
			response.getWriter().write(result.toString()) ;
		return status;
	}

	private Status updateGameType(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String strGameType = request.getParameter(ServletConstants.arg_game_type) ;
		String gameDescription = request.getParameter(ServletConstants.arg_game_description) ;
		String strAnswerType = request.getParameter(ServletConstants.arg_answer_type) ;
		String strAnswerLen = request.getParameter(ServletConstants.arg_answer_len) ;
		String strPoint = request.getParameter(ServletConstants.arg_point) ;
		String strPointWorker = request.getParameter(ServletConstants.arg_point_worker) ;
		String strInterval = request.getParameter(ServletConstants.arg_interval) ;
		String strTransOn = request.getParameter(ServletConstants.arg_trans_on) ;
		String strDifficulty = request.getParameter(ServletConstants.arg_difficulty) ;
		
		if(gameDescription == null || strAnswerType == null || strAnswerLen == null
				|| strPoint == null || strPointWorker == null || strInterval == null || strDifficulty == null)
			return Status.INVALID_ARGUMENT ;
			

		int answerType = 0 ;
		int answerLen = 0 ;
		int point = 0 ;
		double pointWorker = 0 ;
		int interval = 0 ;
		int gameType = 0 ;
		int transOn = 1 ;
		double difficulty = 1.0f ;
		try{
			gameDescription = java.net.URLDecoder.decode(gameDescription,"UTF-8") ;
			answerType = Integer.parseInt(strAnswerType) ;
			answerLen = Integer.parseInt(strAnswerLen) ;
			point = Integer.parseInt(strPoint) ;
			pointWorker = Double.parseDouble(strPointWorker) ;
			interval = Integer.parseInt(strInterval) ;
			gameType = Integer.parseInt(strGameType) ;
			transOn = Integer.parseInt(strTransOn) ;
			difficulty = Double.parseDouble(strDifficulty) ;
		}
		catch(Exception e)
		{
			return Status.INVALID_VALUE ;
		}
		if(gameDescription.length() > 10 || gameDescription.indexOf('"')>=0
				|| gameDescription.indexOf('\'')>=0)
			return Status.INVALID_VALUE ;
		Status status = mserver.s_updateGameType(gameType, gameDescription, point, pointWorker, answerType, answerLen, interval, transOn,difficulty) ;
		
		if(status == Status.OK)
			response.getWriter().write(Status.OK.toString()) ;

		return status;
	}
	

	private Status queryClient(HttpServletRequest request,
			HttpServletResponse response) {

		String clientName = request.getParameter(ServletConstants.arg_client_name) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		
		int pageNo = 1 ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
		PageList pageList = Globals.getClientList(pageNo,clientName);
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<h3>客户端列表</h3>");
		result.append(pageList.getPageInfo().getHtmlByAction("onQueryClient();"));
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>ID</td>");
				result.append("<td>客户端</td>");
				result.append("<td>姓名/手机号</td>");
				result.append("<td>总题数/错题数</td>");
				result.append("<td>正确率</td>");
				result.append("<td>累积点数</td>");
				result.append("<td class=\"action\">操作</td>");
			result.append("</tr>");
			ClientBean client ;
		
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				client = (ClientBean)pageList.getList().get(i) ; 
				result.append("<tr id=").append(client.getClientId()).append(">");
					result.append("<td>").append(client.getClientId()).append("</td>");
					result.append("<td>").append(client.getClientName()).append("</td>");
					result.append("<td>").append(client.getName()).append("/").append(client.getPhone()).append("</td>");
					result.append("<td>").append(client.getAnswered()).append("/").append(client.getWrong()).append("</td>");
//					result.append("<td>").append().append("</td>");
					result.append("<td>").append(client.getAnswered()==0?"-":String.format("%.2f%%", 100.0*(1.0-1.0*client.getWrong()/client.getAnswered()))).append("</td>");
					result.append("<td>").append(client.getPoint()).append("</td>");
					result.append("<td class=\"action\"><a href=\"#\" class=\"edit\" onclick=\"onEditClient(").append(client.getClientId())
						.append("); return false;\">编辑</a><a href=\"\" class=\"delete\" onclick=\"onDeleteClient(").append(client.getClientId())
						.append("); return false;\">删除</a></td>");
	            result.append("</tr>");
			}

        result.append("</table>");
		result.append("<input type=button class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" onclick=\"openCreateClientDlg();\" value=\"新建客户端\"/>") ;
        
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;	
	}
	private Status stasticClient(HttpServletRequest request,
			HttpServletResponse response) {

		String clientName = request.getParameter(ServletConstants.arg_client_name) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		String minStasticTime = request.getParameter(ServletConstants.arg_min_stastic_time) ;
		String maxStasticTime = request.getParameter(ServletConstants.arg_max_stastic_time) ;
		int pageNo = 1 ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
		PageList pageList = Globals.getStasticClientList(pageNo,clientName,minStasticTime,maxStasticTime) ;
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<h3>客户端统计列表</h3>");
		result.append(pageList.getPageInfo().getHtmlByAction("onQueryClient();"));
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>ID</td>");
				result.append("<td>客户端/姓名</td>");
				result.append("<td>总题数/错题数</td>");
				result.append("<td>正确率</td>");
				result.append("<td>累积点数</td>");
			result.append("</tr>");
			StasticClientBean stasticClient ;
			ClientBean clientBean ;
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				stasticClient = (StasticClientBean)pageList.getList().get(i) ; 
				clientBean = Globals.getClientBuffer().getClient(stasticClient.getClientId()) ;
				if (clientBean == null)
					continue ;
				result.append("<tr id=").append(stasticClient.getClientId()).append(">");
					result.append("<td>").append(stasticClient.getClientId()).append("</td>");
					result.append("<td>").append(clientBean.getClientName()).append("/").append(clientBean.getName()).append("</td>");
					result.append("<td>").append(stasticClient.getAnsweredToday()).append("/").append(stasticClient.getWrongToday()).append("</td>");
					result.append("<td>").append(stasticClient.getAnsweredToday()==0?"-":String.format("%.2f%%", 100.0*(1.0-1.0*stasticClient.getWrongToday()/stasticClient.getAnsweredToday()))).append("</td>");
					result.append("<td>").append(stasticClient.getPointToday()).append("</td>");
	            result.append("</tr>");
			}

        result.append("</table>");
        
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;	
	}
	private Status getQueryGameTypeDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>查询条件</h3>");
        		result.append("<fieldset>");
                        	result.append("<p><label>项目类型:</label><input id=gameType type=\"text\" class=\"text-long\" maxlength=4/></p>");
                    		result.append("<input type=\"submit\" value=\"提交查询\" onclick=\"onQueryGameType();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;

		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}

	// 登陆
	private Status login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		Status status = Status.OK ;
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		if (userName == null || password == null)
		{
			status = Status.INVALID_ARGUMENT ;
		} 
		else if (mserver.c2s_checkClientLogin(userName))
		{
			status = Status.CLIENT_LOGIN_ALREADY ;
		}
		else
		{
			status = mserver.s_login(userName,password) ;
			if (status == Status.OK)
			{
				UserBean user = mserver.p2s_getUser(userName) ;
				request.getSession().setAttribute(ServletConstants.s_attr_user, user) ;
				response.sendRedirect("admin_index.html") ;
			}
		}
		return  status;
	}
	/**
	 *  注销
	 * 
	 * */
	private Status logout(HttpServletRequest request, HttpServletResponse response)
	{
		
		try
		{
			request.getSession().removeAttribute(ServletConstants.s_attr_user) ;
	        RequestDispatcher disp = request.getRequestDispatcher("/modules/admin/login.html") ;
	        disp.forward(request, response) ;
		}
		catch(Exception e)
		{
			e.printStackTrace() ;
			logger.error(e.getMessage()) ;
		}
		return Status.OK ;
	}
}
